#!/usr/bin/env python


from paste.fixture import TestApp
from nose.tools import *
from webapp import app

from model import User, Group
from model import commit
import util

def post_form(url, content):
    middleware = []
    test_app = TestApp(app.wsgifunc(*middleware))
    return test_app.post(url)
  
def simple_get(url, required_status, must_haves):
    middleware = []
    test_app = TestApp(app.wsgifunc(*middleware))
    r = test_app.get(url)
    assert_equal(r.status, required_status)
    for m in must_haves:
        r.mustcontain(m)
    return assert_equal(r.status, required_status)
    
def test_user_new_get():
    '''Checks for display of /user/new'''
    url = '/user/new'
    required_status = 200
    must_haves = ['user','new','email']
    simple_get(url, required_status, must_haves)
      
def test_user_get():
    if not User('user4').exists():
        u = User('user4')
        u.email = 'user4@test.com'
        u.password_hash = u.hash('123123')
        u.save()
        commit()  
    url = '/user/user4'
    required_status = 200
    must_haves = ['user4','view','user4@test.com']
    simple_get(url, required_status, must_haves) 
    
    url = '/user/user4/edit'
    required_status = 200
    must_haves = ['user4','edit','user4@test.com']
    simple_get(url, required_status, must_haves)   
    
    url = '/user/user4/groups'
    required_status = 200
    must_haves = ['user4','groups']
    simple_get(url, required_status, must_haves) 
    
    url = '/user/user4/groups/edit'
    required_status = 200
    must_haves = ['user4','tst_group1']
    simple_get(url, required_status, must_haves)
    ## Test using number for id
    u = User('user4').read()
    i = u.id
    url = '/user/{0}'.format(i)
    must_haves = ['user4','view','user4@test.com']
    simple_get(url, required_status, must_haves)
    
    url = '/user/{0}/groups/edit'.format(i)
    required_status = 200
    must_haves = ['user4','tst_group1']
    simple_get(url, required_status, must_haves)
    
def test_user_new_post():
    before = len(User().all()) 
    middleware = []
    test_app = TestApp(app.wsgifunc(*middleware))
    res = test_app.get('/user/new')
    form = res.forms[0]
    name = util.unique_name('fm_')
    form['name'] = name
    form['email']= '{0}@form.tst'.format(name)
    form['password']='123123'
    r = form.submit()
    after = len(User().all())
    assert after == before + 1 
    
def test_user_new_spaceinname_post():
    before = len(User().all()) 
    middleware = []
    test_app = TestApp(app.wsgifunc(*middleware))
    res = test_app.get('/user/new')
    form = res.forms[0]
    # name = util.unique_name('fm_')
    name = 'fred smith'
    form['name'] = name
    form['email']= '{0}@nameinspace.tst'.format(name)
    form['password']='123123'
    r = form.submit()
    after = len(User().all())
    r.mustcontain('Please check')
    assert after == before 
    
def test_user_edit_post():
    name = 'tst_user_edit_post'
    if not User(name).exists():
        u = User(name)
        u.email ='{0}@test.com'.format(name)
        u.password_hash = u.hash('123123')
        u.save()
        commit()
    #get the form     
    middleware = []
    test_app = TestApp(app.wsgifunc(*middleware))
    res = test_app.get('/user/{0}/edit'.format(name))
    form = res.forms[0]
    #set new field values
    form['name'] = name + '2'
    form['email']= '{0}@form.tst'.format(name+'2')
    # form['password']='123123'+'2'
    r = form.submit()
    #check user exists
    url = '/user/tst_user_edit_post2'
    required_status = 200
    must_haves = ['tst_user_edit_post2','tst_user_edit_post2@form.tst']
    simple_get(url, required_status, must_haves)
    #returm user to original status
    u = User('tst_user_edit_post2').read()
    u.name = name 
    u.email ='{0}@test.com'.format(name)
    u.password_hash = u.hash('123123')
    u.save()
    commit()
    
def test_user_group_post():
    name = 'tst_user_edit_post'
    #create the user
    if not User(name).exists():
        u = User(name)
        u.email ='{0}@test.com'.format(name)
        u.password_hash = u.hash('123123')
        u.save()
        commit()
    #get the form     
    middleware = []
    test_app = TestApp(app.wsgifunc(*middleware))
    res = test_app.get('/user/{0}/groups/edit'.format(name))
    form = res.forms[0]
    #create groups
    group_list = ['tst_grpfm_1','tst_grpfm_2','tst_grpfm_3']
    for g in group_list:
        if not Group(g).exists():
            Group(g).save()
    assert commit()[0]
    # add group and set field values
    g1 = Group('tst_grpfm_1').read()
    group_field = 'grpadd{0}'.format(g1.id)
    form[group_field] = 'link'
    level_field = 'levadd{0}'.format(g1.id)
    form[level_field] = '60'
    
    g2 = Group('tst_grpfm_2').read()
    group2_field = 'grpadd{0}'.format(g2.id)
    form[group2_field] = 'link'
    level2_field = 'levadd{0}'.format(g2.id)
    form[level2_field] = '60' 
    form.submit()
    #check that groups are added
    u = User(name).read()
    group_names = [g.name for g in u.groups()]   
    assert len(set(group_names) - set(['tst_grpfm_1','tst_grpfm_2'])) == 0
    #TODO  check membership level
    #----- change level of g1 -----#
    #get the form     
    middleware = []
    test_app = TestApp(app.wsgifunc(*middleware))
    res = test_app.get('/user/{0}/groups/edit'.format(name))
    form = res.forms[0]
      
    g1 = Group('tst_grpfm_1').read()
    group1_field = 'grprem{0}'.format(g1.id)
    form[group1_field] = 'unlink'
    
    g2 = Group('tst_grpfm_2').read()
    level_field = 'levchg{0}'.format(g2.id)
    form[level_field] = '40'
    
    g3 = Group('tst_grpfm_3').read()
    group3_field = 'grpadd{0}'.format(g3.id)
    form[group3_field] = 'link'
    level3_field = 'levadd{0}'.format(g3.id)
    form[level3_field] = '40' 
   
    form.submit()
    u = User(name).read()
    group_names = [g.name for g in u.groups()]
    assert len(set(group_names) - set(['tst_grpfm_2','tst_grpfm_3'])) == 0
    #remove groups from this user
    middleware = []
    test_app = TestApp(app.wsgifunc(*middleware))
    res = test_app.get('/user/{0}/groups/edit'.format(name))
    form = res.forms[0]      
    g2 = Group('tst_grpfm_2').read()
    field = 'grprem{0}'.format(g2.id)
    form[field] = 'unlink'    
    g3 = Group('tst_grpfm_3').read()
    field = 'grprem{0}'.format(g3.id)
    form[field] = 'unlink'  
    form.submit()
    # check the group links are gone
    u = User(name).read()
    assert len(u.groups()) == 0
    
        
if __name__ == '__main__':
    print 'start'
    test_user_get()
#    test_user_new_post()
#    test_user_new_spaceinname_post()
#    test_user_new_get()
#    test_user_edit_post()
#    test_user_group_post()
    
    print 'done'

   
#===============================================================================
#                            | OK  | Failed form | Failed DB | DB Off |
# user/new                       x       x           x           
# user/exists(name)               x
# user/exist(number)              x
# user/notexists(name)            x
# user/notexist(number)           x
# user/exists(name)/edit          x       x           x
# user/exist(number)/edit         x       x           x
# user/notexist(number)/edit      x
# user/notexist(name)/edit        x
#===============================================================================



